from flask import Blueprint, request, send_file
import oss2
import os
import datetime
import jieba

from entity.Response import error,success
from entity.ChatHistory import ChatHistory
from entity.Log import Log
from entity.User import User
from collections import Counter

dataController = Blueprint('dataController',__name__)

auth = oss2.Auth('LTAI5tSXK6NrNBRRKMREWogX', 'VtNmUW6TZt1oJpYskBizw6u0p8bUXw')
bucket = oss2.Bucket(auth,'oss-cn-beijing.aliyuncs.com', 'rubbertreecell')

@dataController.route('/getSegmentationCount',methods=['GET'])
def getSegmentationCount():
    dataList = []
    for i in range(7):
        start_time = datetime.datetime.now() - datetime.timedelta(days=i)
        end_time = start_time + datetime.timedelta(days=1)

        # 查询当天的记录数量
        count = Log.query.filter(Log.create_time >= start_time, Log.create_time < end_time).count()
        dataList.append({
            'date': start_time.strftime('%Y-%m-%d'),
            'count': count
        })

    return dataList

@dataController.route('/getFunctionCount',methods=['GET'])
def getFunctionCount():
    logList = Log.query.all()
    counter = Counter()
    for log in logList:
        counter[log.type] += 1
    counterList = list(counter.items())
    dataList = []
    for (keyword, count) in counterList:
        dataList.append({
            'name': keyword,
            'value':count
        })
    return dataList

@dataController.route('/getActiveUserCount',methods=['GET'])
def getActiveUserCount():
    dataList = []
    for i in range(7):
        start_time = datetime.datetime.now() - datetime.timedelta(days=i)
        end_time = start_time + datetime.timedelta(days=1)

        # 查询当天的记录数量
        count = User.query.filter(User.update_time >= start_time, User.update_time < end_time).count()
        dataList.append({
            'date': start_time.strftime('%Y-%m-%d'),
            'count': count
        })

    return dataList
    pass

@dataController.route('/getWordCloud',methods=['GET'])
def getWordCloud():
    chatHistoryList = ChatHistory.query.all()
    counter = Counter()
    for chatHistory in chatHistoryList:
        words = jieba.cut(chatHistory.content)
        for word in words:
            counter[word] += 1
    counterList = list(counter.items())
    dataList = []
    for (keyword, count) in counterList:
        dataList.append({
            'name': keyword,
            'value':count
        })
    return dataList

def uploadToOSS(file_path):
    # 获取文件名
    file_name = os.path.basename(file_path)

    # 上传到的 OSS 路径
    oss_path = file_name

    # 打开本地文件并上传到 OSS
    with open(file_path, 'rb') as file_obj:
        bucket.put_object(oss_path, file_obj)

    # 设置对象为公开读权限
    bucket.put_object_acl(oss_path, oss2.OBJECT_ACL_PUBLIC_READ)

    # 生成永久有效的访问链接
    share_link = f"https://{bucket.bucket_name}.oss-cn-beijing.aliyuncs.com/{oss_path}"
    return share_link